class GoodsController < ApplicationController
    def find
    end

    def publish
        if user_signed_in?
            @good = current_user.goods.new
        else
            redirect_to new_user_session_path, alert: "You must be signed in to publish goods."
        end
    end

    def list
        if params.has_key?(:goods_region)
            @goods = []
            @users = User.where(region: params[:goods_region])
            @users.each do |user|
                @goods = @goods + user.goods
            end
        else
            @goods = Good.all
        end
        @goods = Good.where.not(status: true).order(created_at: :desc)
    end

    def search
        @search_content = params[:search_content]
        @goods = Good.where("name like ?","%#{@search_content}%")
        @goods = @goods + Good.where("description like ?","%#{@search_content}%")
        @goods = @goods + Good.where("quality like ?","%#{@search_content}%")
        users = User.where("username like ?","%#{@search_content}%")
        users.each do |user|
            @goods = @goods + user.goods
        end
        @goods = @goods.uniq
        @goods = @goods - Good.where(status: true)

    end

    def show
        @good = Good.find_by_id(params[:id])
        @user = @good.user
        @comments = @good.comments
        if user_signed_in?
            @order = current_user.orders.new
        end
    end

    def create
        @good = current_user.goods.create(good_params)
        redirect_to list_goods_path, success: "Successfully publish new goods."
    end

    def destroy
        @good = Good.find(params[:id])
        @good.destroy
        redirect_back(fallback_location: root_path)
    end

    def order
        if user_signed_in?
            @good = Good.find_by_id(params[:id])
            @good.update(status: 1)
            @order = current_user.orders.new
            @order.goodname = @good.name
            @order.good_id = @good.id
            @order.seller = @good.user.username
            @order.price = @good.price
            @order.save
            redirect_to good_path(@good)
        end
    end

    def index
        @goods = current_user.goods
    end

    def edit
        @good = Good.find_by_id(params[:id])
    end

    def update
        @good = Good.find_by_id(params[:id])
        if @good.update(good_params)
            redirect_to user_goods_path(current_user)
        else
            render 'edit'
        end
    end

private
    def good_params
        params.require(:good).permit(:name, :description, :quality, :price, :picture)
    end
end
